<?php

class mvc_dispatcher {
	protected $dir;
	protected $prefix;
	protected $view;

	public function __construct( mvc_view $view, $dir, $prefix = '' ) {
		$this->dir = $dir;
		$this->prefix = $prefix;
		$this->view = $view;
	}

	public function dispatch( $controller, $action ) {
		$class = $this->prefix.$controller;
		$action = 'action_' . ( empty( $action ) ? 'index' : $action );
		@include( $this->dir.$controller.'.php' );

		if( !class_exists( $class, false))
			throw new Exception( 'Ungültiger Controller!' );
		if( !is_subclass_of( $class, 'mvc_controller' ))
			throw new Exception( 'Ungültiger Controller!' );
		if( !method_exists( $class, $action ))
			throw new Exception( 'Ungültige Action!' );

		$object = new $class( $this->view );

		try {
			$this->view->content( $object->$action());
			$this->view->display();
		} catch( mvc_redirect $e ) {
			header( 'Location: '.$e->getMessage());
		} catch( Exception $e ) {
			$this->view->error( $e->getMessage());
			$this->view->display();
		}
	}
}
